package com.tubeonfire.controller.admin;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.tubeonfire.entity.Page;
import com.tubeonfire.model.admin.PageModel;
import com.tubeonfire.util.StringHelper;

@SuppressWarnings("serial")
public class EditPageServlet extends HttpServlet {

	private static final Logger log = Logger.getLogger(EditPageServlet.class
			.getName());

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ServletException {
		try {
			HttpSession session = req.getSession();
			String id = req.getParameter("id");
			Page obj = PageModel.getById(id);
			if (obj != null) {
				req.setAttribute("obj", obj);
				req.setAttribute("action", "edit");
				req.getRequestDispatcher("/admin/form_page.jsp").forward(req,
						resp);
			} else {
				session.setAttribute("error",
						"Page's not exists or has been deleted !");
				resp.sendRedirect("/admin/page/list");
			}
		} catch (Exception e) {
			log.warning(e.toString());
			e.printStackTrace();
			resp.sendError(4004,
					"We are sorry for the inconvenience ! Please try again later !");
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try {
			HttpSession session = req.getSession();
			String id = req.getParameter("id");
			Page obj = PageModel.getById(id);
			if (obj != null) {
				String pageTitle = (String) req.getParameter("pageTitle");
				String pageDescription = (String) req
						.getParameter("pageDescription");
				String pageContent = (String) req.getParameter("pageContent");
				obj.setTitle(pageTitle);
				obj.setAlias(StringHelper.getAliasByLanguage(pageTitle));
				obj.setDescription(pageDescription);
				obj.setContent(pageContent);
				PageModel.insert(obj);
				session.setAttribute("success", "Action success !");
				resp.sendRedirect("/admin/page/edit?id=" + id);
			} else {
				session.setAttribute("error",
						"Page's not exists or has been deleted !");
				resp.sendRedirect("/admin/page/list");
			}
		} catch (Exception e) {
			log.warning(e.toString());
			e.printStackTrace();
			resp.sendError(4004,
					"We are sorry for the inconvenience ! Please try again later !");
		}
	}
}
